package com.bc.bczbweb.common;

import com.bc.bccore.zbconfig.ZbConfig;
import com.bc.commonentity.common.AjaxNotLoginRunTimeException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInteceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!needCheck(request)) {
            return true;
        }
        if (handler instanceof HandlerMethod) {
            // 判断是否登录
            UserContext context = UserContext.getCurrentContext();
            boolean isLogin = context != null;
            if (!isLogin) {
                if (isAjax(request)) {
                    throw new AjaxNotLoginRunTimeException("请重新登录");
                } else {
                    response.setStatus(200);
                    response.setCharacterEncoding("utf-8");
                    response.sendRedirect(ZbConfig.getSitePath());
                    return false;
                }
            }
            if (isLogin) {// 用户登录后，检查用户是否有当前页面的权限，没有则跳转到订单列表页
                // 用户登录后，将当前用户id和名称保存起来，用于记录操作日志
//				request.setAttribute("userID", context.getLoginInfo().getUserId());
//				request.setAttribute("userName", context.getLoginInfo().getLoginName());
//
//				boolean isAllow = UserContext.checkIsAllow(context.getLoginInfo().getUserId(),
//						request.getRequestURL().toString());
//				if (!isAllow) {
//					response.setStatus(403);
//					response.setCharacterEncoding("utf-8");
//					response.getWriter().write("You have no permission to access this pages!");
//					return false;
//				}
            }
        }

        return true;
    }

    private boolean isAjax(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equals("XMLHttpRequest")) {
            return true;
        }
        return false;
    }

    public static boolean needCheck(HttpServletRequest request) {
        if (request.getServletPath().indexOf("/api-docs") >= 0 || request.getServletPath().equals("/alert/heart")
                || request.getServletPath().indexOf("/swagger") >= 0
                || request.getServletPath().indexOf("manage") > 0
                || request.getServletPath().equals("/")
                ) {
            return false;
        }
        return true;
    }
}
